class FeedbacksController < ApplicationController
  # GET /feedbacks
  # GET /feedbacks.xml
  before_filter :login_required
  before_filter :access_control, :only => [:edit, :update]
  
  def index
    @feedbacks = Feedback.find(:all, :order => "rating DESC")
    @user = current_user
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @feedbacks }
    end
  end

  # GET /feedbacks/1
  # GET /feedbacks/1.xml
  def show
    @user = current_user
    @feedback = Feedback.find(params[:id])
  end

  # GET /feedbacks/new
  # GET /feedbacks/new.xml
  def new
    @feedback = Feedback.new

  end

  # GET /feedbacks/1/edit
  def edit
    @feedback = Feedback.find(params[:id])
  end

  # POST /feedbacks
  # POST /feedbacks.xml
  def create
    @feedback = Feedback.new(params[:feedback])
    @feedback.rating = 0

    if @feedback.save
      expire_fragment(:controller => "feedbacks", :action => "index", :action_suffix => "feedback_list")
      flash[:notice] = 'Feedback was successfully created.'
      redirect_to(feedbacks_url)
    else
      render :action => "new" 
    end

  end

  # PUT /feedbacks/1
  # PUT /feedbacks/1.xml
  def update
    @feedback = Feedback.find(params[:id])
    
    if @feedback.update_attributes(params[:feedback])
      expire_fragment(:controller => "feedbacks", :action => "index", :action_suffix => "feedback_list")
      flash[:notice] = 'Feedback was successfully updated.'
      redirect_to(feedbacks_url)
    else
      format.html render :action => "edit"
    end
  end
  
  def vote_up
    feedback = Feedback.find(params[:id])
    if(!feedback.voted_on?(current_user))
      feedback.rating = feedback.rating + 1
      feedback.save
    
      vote = Vote.new
      vote.user = current_user
      vote.feedback = feedback
      vote.save
      
      expire_fragment(:controller => "feedbacks", :action => "index", :action_suffix => "feedback_list")
      flash[:notice] = "Your vote has succesfully been counted."
    else
      flash[:error] = "No cheating! You're only allowed to vote once per feedback."
    end
    redirect_to :action => :index
  end
  
  def mark_done
    if current_user.is_amber?
      feedback = Feedback.find(params[:id])
      feedback.mark_done
      
      expire_fragment(:controller => "feedbacks", :action => "index", :action_suffix => "feedback_list")
      flash[:notice] = "Feedback successfully marked as done."
    else
      flash[:error] = "Sorry, you're not allowed to do that."
    end
    redirect_to :action => :index
  end
  
  def access_control
    if (Feedback.find(params[:id].to_i).user != current_user)
      flash[:error] = "You are not allowed to edit others' feedback."
      redirect_to '/home'
    end
  end

  # DELETE /feedbacks/1
  # DELETE /feedbacks/1.xml
end
